package com.conversationboard.controller;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.config.Configuration;
import com.conversationboard.model.User;
import com.conversationboard.model.adminlog.AdminLog;
import com.conversationboard.model.adminlog.AdminLogEntry;

@WebServlet(name = "ViewAdminLogControllerServlet", urlPatterns = "/ViewAdminLogControllerServlet")
public class ViewAdminLogControllerServlet extends HttpServlet {

	private static final long serialVersionUID = -616148341928871124L;


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		try {
			request.setCharacterEncoding("UTF-8");
			response.setCharacterEncoding("UTF-8");

			User user = User.get(request.getUserPrincipal().getName());

			/*
			 * If the board is configured to let only site admins see this, then
			 * make sure you are one. Don't need to worry about
			 */

			if (!Configuration.getInstance().isDisplayAdminLogToUsers()) {
				if (Configuration.getInstance().isDisplayAdminLogToSiteAdmins() && (!user.isSiteAdmin())) {
					return;
				}
			}

			int pageNumber = Integer.parseInt(request.getParameter("pageNumber"));

			List<AdminLogEntry> log = AdminLog.getInstance().getPage(pageNumber);

			request.setAttribute("log", log);
			request.setAttribute("pageNumber", ++pageNumber);

			RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/adminlog.jsp");
			dispatcher.forward(request, response);

		} catch (NumberFormatException e) {
		} catch (SQLException e) {
			throw new ServletException(e);
		}

	}
}
